package strings;

import java.util.Stack;

/**
 * @author LiangMu
 * @version \$Id: P1.java, v 0.1, 2023年01月05日 13:23 LiangMu Exp $$
 */
public class P1 {
    public static void main(String[] args) {
        System.out.println(reverseWords2("hello world"));
    }

    public static String reverseWords2(String s) {
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();
        int index = 0;
        for (char it : chars) {
            if (Character.isSpaceChar(it)) {
                while (!stack.isEmpty()) {
                    chars[index++] = stack.pop();
                }
                ++index;
            } else {
                stack.push(it);
            }
        }
        while (!stack.isEmpty()) {
            chars[index++] = stack.pop();
        }
        return new String(chars);
    }

    public static String reverseWords(String s) {
        char[] chars = s.toCharArray();
        int i1 = 0, i2 = 0, len = chars.length;
        while (i2 < len) {
            if (Character.isSpaceChar(chars[i2])) {
                while (i1 <= i2) {
                    if (Character.isSpaceChar(chars[i1])) {
                        ++i1;
                    } else {
                        break;
                    }
                }
                reverseChars4Part(chars, i1, i2 - 1);
                i1 = i2;
            }
            ++i2;
        }
        while (i1 <= i2) {
            if (Character.isSpaceChar(chars[i1])) {
                ++i1;
            } else {
                break;
            }
        }
        reverseChars4Part(chars, i1, i2 - 1);
        return new String(chars);
    }

    private static void reverseChars4Part(char[] chars, int start, int end) {
        while (start < end) {
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
            ++start;
            --end;
        }
    }
}
